using UnityEngine;
using DG.Tweening;

public class TreeController : MonoBehaviour
{
    public GameObject woodPrefab;   // 木头预制体
    public int maxAttackCount = 3;  // 最大攻击次数
    public int maxCreateCount = 3;  // 最大生成物品次数
    public float maxOffsetDistance = 1f;  // 随机偏移的最大距离
    public GameObject cutDownParticleSystem;//粒子效果
    public ToolType toolType;

    private int currentCreateCount; // 生成物品次数
    private int currentAttackCount; // 当前攻击次数

    void Start()
    {
        currentAttackCount = 0;
        currentCreateCount = 0;
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        //碰到带Axe标签物体
        if (other.CompareTag("Axe"))
        {
            //只有对应的工具才可以
            if (other.GetComponent<ToolController>().tool.toolType == toolType)
            {
                //生成特效
                Instantiate(cutDownParticleSystem, transform.position, Quaternion.identity);

                //攻击三次生成物品
                if (currentAttackCount >= maxAttackCount)
                {
                    TakeDamage(other.GetComponent<ToolController>().tool);
                    currentAttackCount = 0;
                }
                currentAttackCount++;
            }
            else
            {
                Debug.Log("工具不对");
            }
        }
    }

    public void TakeDamage(Tool tool)
    {
        int minWoodCount = tool.minCount;    // 随机掉落的最小木头数量
        int maxWoodCount = tool.maxCount;    // 随机掉落的最大木头数量
        // 每次受到攻击时，生成随机数量的木头
        int woodCount = Random.Range(minWoodCount, maxWoodCount + 1);
        for (int i = 0; i < woodCount; i++)
        {
            Vector3 randomOffset = new Vector3(Random.Range(-maxOffsetDistance, maxOffsetDistance), Random.Range(-maxOffsetDistance, maxOffsetDistance), 0f);
            GameObject wood = Instantiate(woodPrefab, transform.position + randomOffset, Quaternion.identity);

            // 使用DOJump方法实现物体的弹跳
            wood.transform.DOJump(wood.transform.position + new Vector3(randomOffset.x, randomOffset.y, 0f), 2, 1, 1).SetEase(Ease.OutSine);
        }

        currentCreateCount++;

        // 如果生成物品次数达到最大值，则销毁木头并重置生成物品次数
        if (currentCreateCount >= maxCreateCount)
        {
            Destroy(gameObject);
            currentCreateCount = 0;
        }
    }
}
